package com.entor.springboot201912.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * redisTemplate的封装
 */
@Component
public class RedisUtil<T> {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public RedisUtil(){}
    public RedisUtil(RedisTemplate<String,Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 设置键有效时间
     * @param key
     * @param times（秒）
     * @return
     */
    public boolean setExprise(String key,long times){
        boolean flat = false;
        try {
            if(times>0){
                redisTemplate.expire(key,times, TimeUnit.SECONDS);
            }
            flat = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flat;
    }

    /**
     * 获取缓存有效时间
     * @param key
     * @return
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * 设置到对字符串支持
     * @param key
     * @param value
     * @return
     */
    public boolean setData(String key,Object value){
        boolean flat = false;
        try{
            redisTemplate.opsForValue().set(key,value);
            flat = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flat;
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public Object getData(String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置支持List集合
     * @param key
     * @param list
     * @return
     */
    public boolean setList(String key, List<T> list){
        boolean flat = false;
        try {
            redisTemplate.opsForList().rightPush(key,list);
            flat = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flat;
    }

    /**
     * 获取list缓存内容
     * @param key
     * @param start
     * @param end 0到-1 获取所有
     * @return
     */
    public List<Object> getList(String key,int start,int end){
        return redisTemplate.opsForList().range(key,start,end);
    }

}
